package cn.com.lyb.flink.window;

import cn.com.lyb.flink.bean.WaterSensor;
import cn.com.lyb.flink.split.WaterSensorMapFunction;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.ProcessingTimeSessionWindows;
import org.apache.flink.streaming.api.windowing.assigners.SessionWindowTimeGapExtractor;
import org.apache.flink.streaming.api.windowing.windows.GlobalWindow;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

public class CountWindowDemo {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<WaterSensor> sensorDS = env.socketTextStream("172.32.1.6", 1234).map(new WaterSensorMapFunction());

        KeyedStream<WaterSensor, String> keyBy = sensorDS.keyBy((KeySelector<WaterSensor, String>) waterSensor -> waterSensor.getId());

        WindowedStream<WaterSensor, String, GlobalWindow> sensorWs =
                //keyBy.countWindow(5); // 滚动窗口，窗口长度5条数据
                keyBy.countWindow(5,2);// 滑动窗口，窗口长度5条数据，滑动步长2条数据（每经过一个步长，都有一个窗口触发输出，第一次输出再第2条数据来的时候）
        sensorWs.process(new ProcessWindowFunction<WaterSensor, String, String, GlobalWindow>() {
            @Override
            public void process(String s, Context context, Iterable<WaterSensor> iterable, Collector<String> collector) throws Exception {
                long maxTs = context.window().maxTimestamp();
                String maxTime = DateFormatUtils.format(maxTs, "yyyy-MM-dd HH:mm:ss.SSS");
                long size = iterable.spliterator().estimateSize();
                collector.collect("keys= " + s + "的窗口最大时间=" + maxTime + ",包含" + size + "条数据===>" + iterable.toString());
            }

        }).print();


        env.execute();
    }
}
